import express, { Request, Response } from "express"
import { MenuContext, SystemRouter } from "../../../../context/MenuContext"
import { catchError, useCheckAndResponse } from "../../../../utils/common"
import { checkError } from "../../../../utils/token"
import { AddMenuParam, EditMenuParam, GetMenuParams, MenuItemType, PutMenuStateParams } from "@Tea/model"
import { LoggedInRequest } from "../../../../types"

const menuManage = express.Router()

menuManage.post("/pageList", async (req: Request, res: Response) => { 
  try {
    const data = await MenuContext.getInstance().getSystemMenu(req.body as GetMenuParams)

    res.send({
      code: 1,
      msg: "查询成功",
      data
    })
  } catch (e) {
    res.status(500).send({
      code: 0,
      msg:checkError(e)
    })
  }
})

menuManage.post("/addMenu", async (req: LoggedInRequest, res: Response) => {
  try {
    const params = req.body as AddMenuParam
    const result = await MenuContext.getInstance().addMenu(params, req.userInfo.userId)
    
    useCheckAndResponse(res, result[0], '新增成功')
  } catch (ex) {
    res.status(500).send({
      code: 0,
      msg: checkError(ex)
    })
  }
})

menuManage.put("/editMenu", async (req: LoggedInRequest, res: Response) => {
  try {
    const params = req.body as EditMenuParam
    const result = await MenuContext.getInstance().editMenu(params, req.userInfo.userId)
    
    useCheckAndResponse(res, result[0], '编辑成功')
  } catch (ex) {
    res.status(500).send({
      code: 0,
      msg: checkError(ex)
    })
  }
})

menuManage.post("/deleteMenu", async (req: LoggedInRequest, res: Response) => {
  try {
    const params = req.body as {
      menuIds: MenuItemType["menuId"][]
    }
    console.log(req.body);
    
    const result = await MenuContext.getInstance().deleteMenu(params.menuIds)
    
    useCheckAndResponse(res, result[0][0], '删除成功')
  } catch (ex) {
    res.status(500).send({
      code: 0,
      msg: checkError(ex)
    })
  }
})

menuManage.put("/putMenuState", async (req: LoggedInRequest, res: Response) => {
  catchError(res,async () => {
    const params = req.body as PutMenuStateParams
    const result = await MenuContext.getInstance().putMenuState(params, req.userInfo.userId)
    useCheckAndResponse(res, result[0][0], params.enable === 1 ? "启用成功" : "停用成功")
  })
})

export default menuManage